package com.ocom.mysql;

import com.ocom.common.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * spring动态数据源（需要继承AbstractRoutingDataSource）
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

//    private static final ThreadLocal<DataSource> dataSource = new ThreadLocal<>();
    private static final ThreadLocal<DataSource> dataSource = ThreadLocal.withInitial(() -> (DataSource) SpringUtils.getBean("defaultDataSource"));
    public static void setDataSource(DataSource dataSource) {
        DynamicDataSource.dataSource.set(dataSource);
    }

    public static DataSource getDataSource() {
        return DynamicDataSource.dataSource.get();
    }
    @Override
    protected Object determineCurrentLookupKey() {
        return null;
    }
  /*  @Override
    protected DataSource determineTargetDataSource() {
        return getDataSource();
    }*/

    @Override
    public Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }


    public static void clear() {
        DynamicDataSource.dataSource.remove();
    }

}